using System;
using System.Security;
using System.Security.Cryptography;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using System.Globalization;
using System.Reflection;
using System.Configuration.Assemblies;

using AspNetHost;

using WebServer;

namespace WebServer.Modules
{
	[CoreModule("AspNetDomain", typeof(AspNetDomain), CoreModulePriority.Disabled)]
	public class AspNetDomain
	{
		private static void Start()
		{
			AspNetInitializer.AppName = "/HTDOCS/";

			AspNetInitializer.WorkingDirectory =
				IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/" + Config.SystemName + "/HTDOCS/");

			AspNetInitializer.CachePath =
				IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/" + Config.SystemName + "/Cache/");

			AspNetInitializer.PrivateBinPath =
				IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/");

			AspNetInitializer.Initialize();
		}
	}

	public static class AspNetInitializer
	{
		private static string _PrivateBinPath;
		public static string PrivateBinPath { get { return _PrivateBinPath; } set { _PrivateBinPath = value; } }

		private static string _WorkingDirectory;
		public static string WorkingDirectory { get { return _WorkingDirectory; } set { _WorkingDirectory = value; } }

		private static string _CachePath;
		public static string CachePath { get { return _CachePath; } set { _CachePath = value; } }

		private static string _AppName;
		public static string AppName { get { return _AppName; } set { _AppName = value; } }

		private static AspHost _Instance;
		public static AspHost Instance { get { Create(); return _Instance; } }

		public static void Initialize()
		{
			Create();
		}

		private static void Create()
		{
			try
			{
				if (_Instance == null)
				{
					//_Instance = (AspHost)ApplicationHost.CreateApplicationHost(typeof(AspHost), _AppName, _WorkingDirectory);

					AppDomainSetup setup = new AppDomainSetup();
					setup.ApplicationName = _AppName;
					setup.ApplicationBase = _WorkingDirectory;
					setup.PrivateBinPath = _PrivateBinPath;
					setup.CachePath = _CachePath;

					AppDomain d = AppDomain.CreateDomain("AspNetDomain", null, setup);

					_Instance = (AspHost)d.CreateInstanceFromAndUnwrap("AspNetHost.dll", "AspHost");
				}
			}
			catch (Exception ex)
			{ Console.WriteLine(ex.ToString()); }
		}
	}
}